<template>
  <scroll-view class="preview" :scroll-y="true">
    <view class="preview-phone" v-if="pageData">
      <view
        class="preview-phone-container"
        :style="{
          ...pageData.style,
        }"
      >
        <view class="preview-phone-header">
          <img :src="headerIcon" class="headerIcon" alt="" />
          <view class="navbar">
            <span
              v-if="pageData && pageData.attribute && pageData.attribute.title"
              >{{ pageData.attribute.title }}</span
            >
            <span v-else></span>
          </view>
          <img :src="settingIcon" class="settingIcon" alt="" />
        </view>
        <webchat-info
          v-if="pageData.sign === INDENTIFICATION.USER_CENTER_MODAL" />
        <draggable
          v-model="componentsList"
          @end="setList"
          id="preview-phone"
          ref="previewPhone"
        >
          <view
            :id="item.id"
            v-for="(item, index) in componentsList"
            :key="item.id"
            @dragover="onDragoverSetAddComID(item.id)"
            @dragstart="onDragstartMoveCom(item.id)"
            @click.stop.prevent="onClickSetActiveConfigCom(item)"
            class="preview-phone-container-component-container"
          >
            <view
              v-if="!isStartShotCover"
              class="preview-phone-container-op"
              :key="item.id"
            >
              <u-icon
                v-if="!item.isOnly"
                name="/static/widget/copy_com.png"
                size="25"
                @click="onClickCopyCom(item)"
              />
              <u-icon
                name="trash"
                size="20"
                color="#000000"
                @click="onClickDelCom(item)"
              />
            </view>
            <view
              class="preview-phone-container-shape"
              :class="{
                'preview-phone-container-active-component-container':
                  item.id === editConfigComActiveId,
                'preview-phone-container-empty-title':
                  cusFormEmptyTipIds.includes(item.id),
              }"
            >
              <span style="margin-left: 5px">
                {{ item.type | getComponentName }}</span
              >
            </view>
            <view
              class="preview-phone-container-tipIds"
              v-if="cusFormEmptyTipIds.includes(item.id)"
              :class="{
                'preview-phone-container-empty-title':
                  cusFormEmptyTipIds.includes(item.id),
              }"
            >
              <span> 标题未填 </span>
            </view>
            <view class="preview-phone-container-component" :key="index">
              <component
                :class="{
                  'preview-phone-container-active-component-container':
                    item.id === editConfigComActiveId,
                }"
                style="pointer-events: none"
                :is="item.type"
                :attribute="item.attribute"
                :styles="item.style"
              />
            </view>
          </view> </draggable
      ></view>
    </view>
  </scroll-view>
</template>

<script>
import { CONFIG } from "@/components/materals/index";
import html2canvas from "html2canvas";
import { uploadImage } from "@/service/api/base";
import webchatInfo from "@/components/wechat-info";
import { INDENTIFICATION } from "@/const/widget";

export default {
  name: "index",
  components: { webchatInfo },
  computed: {
    pageData() {
      return this.$store.state.page.page;
    },
    components() {
      return this.$store.state.page.page.items;
    },
    activeComponentJSON() {
      return this.$store.state.page.activeComponentJSON;
    },
    editConfigComActiveId() {
      return this.$store.state.page.editConfigComActiveId;
    },
    cusFormEmptyTipIds() {
      return this.$store.state.page.cusFormEmptyTipIds;
    },
  },
  data() {
    return {
      INDENTIFICATION,
      componentsList: this.$store.state.page.page.items,
      addActiveID: null,
      headerIcon: require("@/static/widget/header.png"),
      settingIcon: require("@/static/widget/setting.png"),
      isStartShotCover: false,
    };
  },
  watch: {
    addActiveID(newId) {
      // console.log("设置新激活的组件id", newId);
      this.$nextTick(() => {
        document.getElementById(newId).addEventListener(
          "dragover",
          (event) => {
            if (this.activeComponentJSON.type === "add")
              uni.$u.throttle(this.onDragover(event), 500);
          },
          false
        );
      });
    },
    components(val) {
      this.componentsList = Object.assign([], val);
    },
    // pageData: {
    //   handler(cal) {
    //     console.log("dom更新", cal);
    //     uni.$u.debounce(this.handleShotPreviewCover, 1500);
    //   },
    //   deep: true,
    // },
  },
  mounted() {},
  filters: {
    getComponentName(type) {
      // // console.log(
      //   "组件中文",
      //   CONFIG.filter((v) => v.type === type)
      // );
      return CONFIG?.filter((v) => v.type === type)[0]?.name || "";
    },
  },
  methods: {
    setList(e) {
      if (this.activeComponentJSON.type !== "move") return;
      const { newIndex, oldIndex } = e;
      // console.log("移动了", newIndex, oldIndex);
      const params = {
        json: this.activeComponentJSON.json,
        newIndex,
        oldIndex,
      };
      this.$store.dispatch("page/setMovePageComponents", params).then(() => {
        this.$store.dispatch("page/setEditConfigComActiveId", params?.json?.id);
      });
    },
    onDragover(e) {
      e.preventDefault();
      e.stopPropagation();
      let [y, h] = [e.offsetY, e.target.offsetHeight];
      const direction = y < h / 2;
      const index = this.componentsList.findIndex(
        (v) => v.id === this.addActiveID
      );
      const addIndex = direction ? index : index + 1;
      // console.log("addIndex", addIndex);
      this.$store.dispatch("page/setAddPageComponentIndex", addIndex);
    },
    onDragoverSetAddComID(id) {
      // console.log("onDragoverSetAddComID", this.activeComponentJSON, id);
      if (this.activeComponentJSON.type === "add") {
        //设置添加组件的时候的激活的组件id
        // // console.log("设置添加组件的时候的激活的组件id", id);
        this.addActiveID = id;
      }
    },
    onDragstartMoveCom(id) {
      const moveJson = this.componentsList.filter((v) => v.id === id)[0];
      // console.log("设置移动的id", id, moveJson);
      const params = {
        type: "move",
        json: JSON.parse(JSON.stringify(moveJson)),
      };
      this.$store.dispatch("page/setPageComponentJSON", params).then(() => {
        this.$store.dispatch("page/setEditConfigComActiveId", params?.json?.id);
      });
    },
    onClickSetActiveConfigCom(item) {
      this.$store.dispatch("page/setEditConfigComActiveId", item?.id);
    },
    //删除/复制操作
    onClickCopyCom(json) {
      const component = JSON.parse(JSON.stringify(json));
      const addIndex = this.pageData.items.findIndex((v) => v.id === json.id);
      component.id = `${Date.now()}`;
      const params = {
        type: "add",
        json: component,
      };
      this.$store.dispatch("page/setAddPageComponentIndex", addIndex + 1);
      this.$store.dispatch("page/setPageComponentJSON", params).then(() => {
        this.$store.dispatch("page/setAddPageComponent").then(() => {
          this.$store.dispatch("page/setPageComponentJSON", {});
          this.$store.dispatch("page/setAddPageComponentIndex", -1);
        });
      });
    },
    onClickDelCom(json) {
      const delIndex = this.pageData.items.findIndex((v) => v.id === json.id);
      this.$store.dispatch("page/delComponent", delIndex).then(() => {
        setTimeout(() => {
          const editId = this.pageData.items[delIndex - 1]?.id;
          if (editId) {
            // console.log("delIndex", delIndex - 1, editId);
            this.$store.dispatch("page/setEditConfigComActiveId", editId);
          } else {
            const firstId = this.pageData.items[0]?.id;
            if (!firstId) return;
            this.$store.dispatch("page/setEditConfigComActiveId", firstId);
          }
        }, 200);
      });
    },
    handleShotPreviewCover() {
      return new Promise((resolve, reject) => {
        this.isStartShotCover = true;
        this.$nextTick(() => {
          let canvasBox = document.getElementById("preview-phone");
          const config = {
            useCORS: true,
            allowTaint: true,
            width: canvasBox.offsetWidth, //48为padding值
            height: canvasBox.clientHeight, //可见高度+padding+margin
            // y: window.pageYOffset + 100, //滚动条高度修复
            scrollX: 17,
          };
          html2canvas(canvasBox, config)
            .then((canvas) => {
              const capture = canvas.toDataURL("image/png");
              let blob = this.dataURLtoFile(capture, "image/jpeg");
              let fileOfBlob = new File([blob], new Date().getTime() + ".jpg");
              uploadImage(null, null, null, fileOfBlob).then((res) => {
                const url = res.baseUrl + res.path;
                this.$store.dispatch("page/setShotCover", url);
                console.log("截图链接", url);
                this.isStartShotCover = false;
                resolve(url || "");
              });

              // this.pageData.attribute.shotCover = url;
            })
            .catch(() => {
              reject();
            });
        });
      });
    },
    dataURLtoFile(dataURI, type) {
      let binary = atob(dataURI.split(",")[1]);
      let array = [];
      for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], { type: type });
    },
  },
};
</script>

<style scoped lang="scss">
$deviceWidth: 375px;
.preview {
  background-color: white;
  overflow: hidden;
  overflow-y: scroll;
  height: 94vh;
  &-phone {
    display: flex;
    justify-content: center;
    margin: 0;
    box-sizing: border-box;
    padding: 48px 13px 48px 25px;
    background-color: whitesmoke;
    min-height: 94vh;
    overflow: hidden;
    overflow-y: scroll;
    &-header {
      width: $deviceWidth;
      height: 100px;
      background-color: white;
      position: relative;
      .headerIcon {
        width: 100%;
        height: 100%;
        display: block;
      }
      .title {
        font-size: 1.125rem;
        color: #2c405a;
      }
      .navbar {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        align-items: center;
        font-size: 1.125rem;
        color: #2c405a;
      }
      .settingIcon {
        height: 32px;
        width: 80px;
        position: absolute;
        top: 49px;
        right: 10px;
      }
    }
    &-container {
      object-fit: contain;
      width: $deviceWidth;
      min-height: 94vh;
      box-sizing: border-box;
      border: 1px solid white;
      &-component-container {
        position: relative;
      }
      &-empty-title {
        color: $u-error !important;
      }
      &-op {
        position: absolute;
        top: 0;
        right: 0;
        z-index: 999;
        margin-left: 5px;
        display: flex;
        align-items: center;
        background-color: rgba(0, 0, 0, 0.1);
      }
      &-shape {
        position: absolute;
        right: -80px;
        top: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 4.5rem;
        height: 25px;
        font-size: 0.5rem;
        color: #333;
        background: #fff;
        box-shadow: 0 0.1rem 0.20666667rem rgba(0, 0, 0, 0.1);
        &:after {
          content: "";
          position: absolute;
          right: 100%;
          top: 0.5rem;
          width: 0;
          height: 0;
          border-width: 5px;
          border-style: solid;
          border-color: transparent;
          margin-bottom: -0.02666667rem;
          border-right-width: 5px;
          border-right-color: currentColor;
          color: #fff;
        }
      }

      &-tipIds {
        position: absolute;
        right: -180px;
        top: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80px;
        height: 25px;
        font-size: 0.5rem;
        color: #333;
      }
      &-component {
        width: 100%;
        margin: 0;
        overflow: hidden;
      }
      &-active-component-container {
        border: 1px dashed $base-color;
        margin: 0 -1px;
      }
    }
  }
}
</style>
